package com.easy.service.Impl;

import com.easy.bean.User;
import com.easy.mapper.UserMapper;
import com.easy.service.UserService;
import com.easy.util.Page;
import com.easy.util.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true) // 默认只读
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class) // 写操作
    public User add(User user) {
        user.setPassword(PasswordUtils.encrypt(user.getPassword()));
        // 新增用户时，默认角色设为普通用户（user）
        if (user.getRole() == null || user.getRole().trim().isEmpty()) {
            user.setRole("user");
        }
        // 执行新增
        userMapper.add(user);
        // 返回新增后的用户信息（包含role）
        //通过主键查询数据库
        return userMapper.one(user.getUser_id());
    }

    // 其他方法（del、edit、all等）保持不变...
    @Override
    @Transactional(rollbackFor = Exception.class) // 写操作
    @CacheEvict(value = "user",key = "#p0",allEntries = true)
    public int del(Integer id) {
        return userMapper.del(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 写操作
    @CachePut(value = "user",key = "'one_'+#p0.user_id")
    public User edit(User user) {
        userMapper.edit(user);
        return userMapper.one(user.getUser_id());
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 写操作
    @Cacheable(value = "user",key = "'all_' + #p0")
    public List<User> all(User user) {
        return userMapper.all(user);
    }

    //将方法返回的对象放入缓存中
    @Override
    @Transactional(rollbackFor = Exception.class) // 写操作
    @Cacheable(value = "user",key = "'one_' + #p0")
    public User one(Integer id) {
        return userMapper.one(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 写操作
    //@Cacheable(value = "user",key = "'page_' + #p1.username + #p1.real_name + #p1.phone + #p0.current + #p0.limit + #p0.data")
    public void page(Page page, User user){
        System.out.println("page");
        int count=userMapper.pageCount(user);
        Object data=userMapper.page(page,user);
        page.setCount(count);
        page.setData(data);
    }
}